package com.jdd.modules.device.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdd.common.api.vo.Result;
import com.jdd.common.aspect.annotation.AutoLog;
import com.jdd.common.system.query.QueryGenerator;
import com.jdd.common.util.LoginUserUtils;
import com.jdd.common.util.SnowFlakeUtil;
import com.jdd.common.util.excel.entity.params.ExportParams;
import com.jdd.common.util.excel.entity.params.ImportParams;
import com.jdd.common.util.excel.util.ExcelImportUtil;
import com.jdd.common.util.excel.web.entity.vo.NormalExcelConstants;
import com.jdd.common.util.excel.web.view.EasypoiSingleExcelView;
import com.jdd.dao.entity.*;
import com.jdd.dao.service.*;
import com.jdd.modules.device.entity.TDevice;
import com.jdd.modules.device.service.TDeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 门禁设备
 * @Author: jdd
 * @Date: 2022-04-20
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "门禁设备")
@RestController("DeviceController")
@RequestMapping("/device")
public class TDeviceController {
    @Autowired
    private TDeviceService deviceService;

    @Resource
    private ITHouseService houseService;

    @Resource
    private ITFloorService floorService;

    @Resource
    private ITUnitService unitService;

    @Resource
    private ITBuildingService buildingService;

    @Resource
    private TAreaService areaService;

    @Resource
    private TProjectService projectService;

    /**
     * 分页列表查询
     *
     * @param device
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "门禁设备-分页列表查询")
    @ApiOperation(value = "门禁设备-分页列表查询", notes = "门禁设备-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<TDevice>> queryPageList(TDevice device,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        Result<IPage<TDevice>> result = new Result<>();
        List<String> projectCodeList = LoginUserUtils.getLoginUser().getProjectCodes();
        if (projectCodeList.isEmpty()) {
            return result;
        }
        Page<TDevice> page = new Page<>(pageNo, pageSize);
        IPage<TDevice> pageList = deviceService.findAllDevice(page, device, projectCodeList);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    @AutoLog(value = "开关门")
    @ApiOperation(value = "开关门", notes = "开关门")
    @GetMapping(value = "/openDoor")
    public Result<TDevice> openDoor(@RequestParam(name = "sn") String sn, HttpServletRequest req) {
        Result<TDevice> result = new Result<>();
        try {
            deviceService.openDoor(sn);
        }catch (Exception e){
            log.error("发送指令失败",e);
            result.setMessage("发送指令失败");
            result.setSuccess(false);
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 添加
     *
     * @param device
     * @return
     */
    @AutoLog(value = "门禁设备-添加")
    @ApiOperation(value = "门禁设备-添加", notes = "门禁设备-添加")
    @PostMapping(value = "/add")
    public Result<TDevice> add(@RequestBody TDevice device) {
        Result<TDevice> result = new Result<>();
        try {
            String parentCode;
            if (device.getId() != null && StringUtils.isNotEmpty(device.getId())) {
                parentCode =  getParentCode(device);
                if(StringUtils.isEmpty(parentCode)){
                    result.error500("在设置父级编号时发生错误");
                    return result;
                }
                device.setParentCode(parentCode);
                updateDeviceAlias(device, parentCode);
                boolean ok = deviceService.updateById(device);
                if (ok) {
                    result.success("修改成功!");
                    return result;
                }
            }
            device.setId(SnowFlakeUtil.getId());
            String deviceSn = device.getDeviceSn();
            parentCode =  getParentCode(device);
            if(StringUtils.isEmpty(parentCode)){
                result.error500("在设置父级编号时发生错误");
                return result;
            }
            device.setParentCode(parentCode);
            updateDeviceAlias(device, parentCode);
            LambdaQueryWrapper<TDevice> tDeviceLambdaQueryWrapper = new LambdaQueryWrapper<>();
            tDeviceLambdaQueryWrapper.eq(TDevice::getDeviceSn,deviceSn);
            TDevice tDevice = deviceService.getOne(tDeviceLambdaQueryWrapper);
            if (tDevice!=null){
                result.error500("设备sn重复");
                return result;
            }
            log.info("device:{}", device);
            deviceService.save(device);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    private void updateDeviceAlias(TDevice device, String parentCode) {
        /*对别名中的区域进行修改*/
        String[] as = parentCode.split("A");
        /*如果分成段数超过2则要对别名进行处理*/
        if (as.length>2){
            ArrayList<String> areaCode = new ArrayList<>();
            for (int i = 1; i < as.length-1; i++) {
                areaCode.add(as[i]);
            }
            LambdaQueryWrapper<TArea> areaLambdaQueryWrapper = new LambdaQueryWrapper<>();
            areaLambdaQueryWrapper.in(TArea::getCode,areaCode);
            List<TArea> areaList = areaService.list(areaLambdaQueryWrapper);
            String areaName = "";
            for (TArea tArea : areaList) {
                areaName += "-"+tArea.getName();
            }
            String deviceAlias = device.getDeviceAlias();
            String[] split = deviceAlias.split("-");
            String newName="";
            split[0] = split[0] + areaName;
            for (int i = 0; i < split.length; i++) {
                if (i >0){
                    newName = newName +"-"+split[i] ;
                }else{
                    newName = newName + split[i];
                }
            }
            device.setDeviceAlias(newName);
        }
    }

    private String getParentCode(TDevice device) {
        if (StringUtils.isNotEmpty(device.getHouseId())){
            THouse house = houseService.getById(device.getHouseId());
            return house.getParentCode()+"H"+house.getCode();
        }else if(StringUtils.isNotEmpty(device.getFloorId())){
            TFloor floor = floorService.getById(device.getFloorId());
            return floor.getParentCode() + "F" +floor.getCode();
        }else if(StringUtils.isNotEmpty(device.getUnitId())){
            TUnit unit = unitService.getById(device.getUnitId());
            return unit.getParentCode() + "U"+unit.getCode();
        }else if (StringUtils.isNotEmpty(device.getBuildingId())){
            TBuilding building = buildingService.getById(device.getBuildingId());
            return building.getParentCode()+"B"+building.getCode();
        }else if (StringUtils.isNotEmpty(device.getAreaId())){
            TArea area = areaService.getById(device.getAreaId());
            return area.getParentCode() + "A" +area.getCode();
        }
        return null;
    }


    /**
     * 编辑
     *
     * @param device
     * @return
     */
    @AutoLog(value = "门禁设备-编辑")
    @ApiOperation(value = "门禁设备-编辑", notes = "门禁设备-编辑")
    @PutMapping(value = "/edit")
    public Result<TDevice> edit(@RequestBody TDevice device) {
        Result<TDevice> result = new Result<>();
        TDevice deviceEntity = deviceService.getById(device.getId());
        if (deviceEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = deviceService.updateById(device);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "门禁设备-通过id删除")
    @ApiOperation(value = "门禁设备-通过id删除", notes = "门禁设备-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            deviceService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "门禁设备-批量删除")
    @ApiOperation(value = "门禁设备-批量删除", notes = "门禁设备-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<TDevice> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<TDevice> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.deviceService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "门禁设备-通过id查询")
    @ApiOperation(value = "门禁设备-通过id查询", notes = "门禁设备-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<TDevice> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<TDevice> result = new Result<>();
        TDevice device = deviceService.getById(id);
        if (device == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(device);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response, TDevice device) {
        // Step.1 组装查询条件
        QueryWrapper<TDevice> queryWrapper = QueryGenerator.initQueryWrapper(device, request.getParameterMap());

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new EasypoiSingleExcelView());
        List<TDevice> pageList = deviceService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "门禁设备列表");
        mv.addObject(NormalExcelConstants.CLASS, TDevice.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("门禁设备列表数据", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = ImportParams.builder().build();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<TDevice> listDevices = ExcelImportUtil.importExcel(file.getInputStream(), TDevice.class, params);
                deviceService.saveBatch(listDevices);
                return Result.ok("文件导入成功！数据行数:" + listDevices.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    @PostMapping(value = "/getBindDevice")
    public Result<?> getBindDevice(@RequestBody TDevice device) {
        LambdaQueryWrapper<TDevice> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(device.getHouseId())) {
            queryWrapper.eq(TDevice::getHouseId, device.getHouseId());
            Result<List<TDevice>> result = new Result<>();
            result.setResult(deviceService.list(queryWrapper));
            return result;
        }
        queryWrapper.isNull(TDevice::getHouseId);
        if (StringUtils.isNotBlank(device.getFloorId())) {
            queryWrapper.eq(TDevice::getFloorId, device.getFloorId());
            Result<List<TDevice>> result = new Result<>();
            result.setResult(deviceService.list(queryWrapper));
            return result;
        }
        queryWrapper.isNull(TDevice::getFloorId);
        if (StringUtils.isNotBlank(device.getUnitId())) {
            queryWrapper.eq(TDevice::getUnitId, device.getUnitId());
            Result<List<TDevice>> result = new Result<>();
            result.setResult(deviceService.list(queryWrapper));
            return result;
        }
        queryWrapper.isNull(TDevice::getUnitId);
        if (StringUtils.isNotBlank(device.getBuildingId())) {
            queryWrapper.eq(TDevice::getBuildingId, device.getBuildingId());
            Result<List<TDevice>> result = new Result<>();
            result.setResult(deviceService.list(queryWrapper));
            return result;
        }
        queryWrapper.isNull(TDevice::getBuildingId);
        queryWrapper.eq(TDevice::getAreaId, device.getAreaId());
        Result<List<TDevice>> result = new Result<>();
        result.setResult(deviceService.list(queryWrapper));
        return result;
    }

}
